//
//  TextField.swift
//  SwiftHub
//
//  Created by Khoren Markosyan on 1/4/17.
//  Copyright © 2017 Khoren Markosyan. All rights reserved.
//

import UIKit
import RxTheme
import RxSwift
import RxCocoa

class TextField: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)
        makeUI()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        makeUI()
    }

    override var placeholder: String? {
        didSet {
            themeService.switch(themeService.type)
        }
    }

    func makeUI() {
        theme.textColor = themed { $0.text }
        theme.tintColor = themed { $0.secondary }
        theme.placeholdColor = themed { $0.textGray }
        theme.borderColor = themed { $0.text }
        theme.keyboardAppearance = themed { $0.keyboardAppearance }
        theme.backgroundColor = themed { $0.primary }
        
        layer.masksToBounds = true
        layerBorderWidth = Configs.BaseDimensions.borderWidth
        layerCornerRadius = Configs.BaseDimensions.cornerRadius

        snp.makeConstraints { (make) in
            make.height.equalTo(Configs.BaseDimensions.textFieldHeight)
        }
    }
}

extension ThemeProxy where Base: UITextField {
    /// (set only) bind a stream to textColor
    var placeholdColor: ThemeAttribute<UIColor> {
        get { fatalError("set only") }
        set {
            guard let holder = base.placeholder, !holder.isEmpty else { return }
            base.setPlaceHolderTextColor(newValue.value)
            let disposable = newValue.stream
                .map {
                    NSAttributedString(string: holder, attributes: [.foregroundColor: $0])
                }
                .take(until: base.rx.deallocating)
                .observe(on: MainScheduler.instance)
                .bind(to: base.rx.attributedPlaceholder)
            hold(disposable, for: "placeholdColor")
        }
    }
    
    /// (set only) bind a stream to textColor
    var borderColor: ThemeAttribute<UIColor> {
        get { fatalError("set only") }
        set {
            let disposable = newValue.stream
                .take(until: base.rx.deallocating)
                .observe(on: MainScheduler.instance)
                .bind(to: base.rx.layerBorderColor)
            hold(disposable, for: "borderColor")
        }
    }
}
